package br.com.Servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import br.com.Dao.PaginaDao;

/**
 * Servlet implementation class uploadImgProduto
 */
@WebServlet("/admin/uploadImgProduto")
public class uploadImgProduto extends HttpServlet {
	private static final long serialVersionUID = 1L;
	String saveFile = "C:/Users/japao/workspace4/plataforma_marketing/WebContent/img/product";
    /**
     * @see HttpServlet#HttpServlet()
     */
    public uploadImgProduto() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// System.out.print(request.getParameter("idPagina"));
		response.setContentType("text/html;charset=UTF-8");
		String nameCapa = "";
		String id = "";
		PaginaDao dao = new PaginaDao();

		// System.out.print(request.getParameter("file"));

		PrintWriter out = response.getWriter();
		try {

			boolean ismultipart = ServletFileUpload.isMultipartContent(request);
			if (ismultipart) {
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				List items = null;
				

				try {
					items = upload.parseRequest(request);
				} catch (Exception e) {
				}
				Iterator itr = items.iterator();

				while (itr.hasNext()) {
					FileItem item = (FileItem) itr.next();

					if (item.getFieldName().equals("idPagina")) {

						//System.out.print("entro aqui");
						//id = item.getString();
						//System.out.print(""+id);
					}
					

					if (!item.isFormField()) {

						String itemname = item.getName();
						if ((itemname == null) || (itemname.equals(""))) {

							continue;

						} else {

							String filename = FilenameUtils.getName(itemname);
							nameCapa = filename;
							File f = checkExist(filename);
							item.write(f);

						}

					}
					
					
				}

				// dao.addCapa(nameCapa, idPage);

			}

		} catch (Exception e) {

		} finally {

		}
		
		// dao.addCapa(nameCapa, Integer.parseInt(id));
		 response.sendRedirect("/plataforma_marketing/admin/cadastrar_produto.jsp?check-upload=true&nameImg="+nameCapa+"");
	}

	private File checkExist(String fileName) {

		System.out.print("\n->"+fileName);

		File f = new File(saveFile + "/" + fileName);

		if (f.exists()) {
			StringBuffer sb = new StringBuffer(fileName);
			sb.insert(sb.lastIndexOf("."), "-" + new Date().getTime());
			f = new File(saveFile + "/" + sb.toString());

		}
		return f;
	}

}
